package niu.toy.spring.mvc;

import cn.hutool.core.collection.CollUtil;



import java.util.HashMap;
import java.util.Map;

/**
 * 封装模型数据和视图
 */
public class ModelAndView {

    private Object view;

    private Map<String,Object> model;

    private int  status;

    /**
     * 没有模型数据，只有视图名称
     * @param viewName 视图名称
     */
    public ModelAndView(String viewName) {
        this.view = viewName;
    }

    /**
     * 同上，区别View支持渲染
     * @param view 拥有render方法的View对象
     */
    public ModelAndView(View view) {
        this.view = view;
    }

    public void clear() {
        this.view = null;
        this.model = null;
    }

    public boolean isEmpty() {
        return (this.view == null && CollUtil.isEmpty(this.model));
    }
    /**
     *
     * @param viewName 视图名称
     * @param model    模型数据
     */
    public ModelAndView(String viewName,  Map<String, ?> model) {
        this.view = viewName;
        if (model != null) {
            getModel().putAll(model);
        }
    }

    /**
     *
     * @param view  视图对象
     * @param model 模型数据
     */
    public ModelAndView(View view,  Map<String, ?> model) {
        this.view = view;
        if (model != null) {
            getModel().putAll(model);
        }
    }

    /**
     * 设置视图名称
     * @param viewName
     */
    public void setViewName( String viewName) {
        this.view = viewName;
    }
    public String getViewName() {
        return (this.view instanceof String ? (String) this.view : null);
    }

    /**
     *  若view是字符串则需要视图解析器 a ViewResolver.
     */
    public boolean isViewReference() {
        return (this.view instanceof String);
    }

    public View getView() {
        return (this.view instanceof View ? (View) this.view : null);
    }
    public void setView( View view) {
        this.view = view;
    }
    /**
     * 获取模型
     * @return
     */
    public Map<String, Object> getModel() {
        if (this.model == null) {
            this.model = new HashMap<>();
        }
        return this.model;
    }

    public ModelAndView addObject(String attributeName, Object attributeValue) {
        getModel().put(attributeName, attributeValue);
        return this;
    }

    public ModelAndView addAllObjects( Map<String, ?> modelMap) {
        getModel().putAll(modelMap);
        return this;
    }

    public int getStatus() {
        return status;
    }

    public void setStatus(int status) {
        this.status = status;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder("ModelAndView: ");
        if (isViewReference()) {
            sb.append("reference to view with name '").append(this.view).append("'");
        }
        else {
            sb.append("materialized View is [").append(this.view).append(']');
        }
        sb.append("; model is ").append(this.model);
        return sb.toString();
    }
}
